<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { parseNovelUrl } from '@/api/import'
import BaseButton from '@/components/ui/BaseButton.vue'
import { safeAreaInsets } from '@/utils/systemInfo'

defineOptions({
  name: 'SearchPage',
})
definePage({
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '搜索导入',
  },
})

// 搜索关键词
const searchKeyword = ref('')

// 支持的平台列表（用于自动识别）
const supportedPlatforms = ref([
  { id: 'fanqie', name: '番茄小说', icon: 'fas fa-apple-alt', color: '#ff6b35', domains: ['fanqienovel.com', 'changdunovel.com'] },
  { id: 'qidian', name: '起点读书', icon: 'fas fa-book', color: '#ff4444', domains: ['qidian.com'] },
  { id: 'jjwxc', name: '晋江文学城', icon: 'fas fa-feather', color: '#f59e0b', domains: ['jjwxc.net'] },
  { id: 'zongheng', name: '纵横中文网', icon: 'fas fa-dragon', color: '#8b5cf6', domains: ['zongheng.com'] },
])

// 导入链接
const importUrl = ref('')

// 识别到的平台
const detectedPlatform = ref('')

// 搜索历史
const searchHistory = ref([
  '霸道总裁的契约新娘',
  '末世重生囤货',
  '修仙从无敌开始',
])

// 热门搜索
const hotSearches = ref([
  { rank: 1, keyword: '现代言情', type: 'top1' },
  { rank: 2, keyword: '重生逆袭', type: 'top2' },
  { rank: 3, keyword: '玄幻修仙', type: 'top3' },
  { rank: 4, keyword: '末世囤货', type: 'other' },
  { rank: 5, keyword: '甜宠文', type: 'other' },
  { rank: 6, keyword: '都市爽文', type: 'other' },
])

// 搜索结果
const searchResults = ref([])
const showResults = ref(false)

// 执行搜索
function handleSearch() {
  const keyword = searchKeyword.value.trim()
  if (!keyword) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'error',
    })
    return
  }

  // 添加到搜索历史
  addToHistory(keyword)

  // 模拟搜索结果
  const mockResults = [
    {
      id: 1,
      title: `${keyword}相关小说1`,
      author: '知名作者',
      platform: '番茄小说',
      description: '这是一本非常精彩的小说，情节跌宕起伏...',
      cover: `https://picsum.photos/seed/${keyword}1/80/120.jpg`,
      viewCount: 12.3,
      likeCount: 8.9,
    },
    {
      id: 2,
      title: `${keyword}相关小说2`,
      author: '网络作家',
      platform: '起点读书',
      description: '精彩的故事内容，值得一读...',
      cover: `https://picsum.photos/seed/${keyword}2/80/120.jpg`,
      viewCount: 8.7,
      likeCount: 6.2,
    },
  ]

  searchResults.value = mockResults
  showResults.value = true

  uni.showToast({
    title: `找到${mockResults.length}个相关结果`,
    icon: 'success',
  })
}

// 导入小说
async function handleImport() {
  const url = importUrl.value.trim()
  if (!url) {
    uni.showToast({
      title: '请输入小说分享链接',
      icon: 'error',
    })
    return
  }

  // 处理多个URL的情况
  const urls = url.split('\n').filter(u => u.trim()).map(u => u.trim())

  if (urls.length === 0) {
    uni.showToast({
      title: '请输入有效的小说分享链接',
      icon: 'error',
    })
    return
  }

  // 检查URL长度，给出警告但允许继续
  if (urls.some(u => u.length > 1000)) {
    console.warn('检测到超长URL，可能是分享链接')
  }

  // 目前只处理第一个URL，后续可以扩展批量导入
  const firstUrl = urls[0]

  // 检查链接格式
  const platform = parsePlatform(firstUrl)
  if (!platform) {
    uni.showToast({
      title: '不支持的链接格式',
      icon: 'error',
    })
    return
  }

  // 显示加载状态
  uni.showLoading({
    title: '正在解析链接...',
    mask: true,
  })

  try {
    // 调用解析接口
    const res = await parseNovelUrl({ url: firstUrl })
    // const response = res.data
    uni.hideLoading()
    uni.showToast({
      title: res.message,
      icon: 'success',
    })

    importUrl.value = ''
    // console.log('解析结果:', response)
    // if (response && (response as any).title) {
    //   // 解析成功，跳转到导入详情页
    //   uni.showToast({
    //     title: '解析成功！',
    //     icon: 'success',
    //   })

    //   setTimeout(() => {
    //     // 将数据存储到 localStorage
    //     const importDataKey = `import_data_${Date.now()}`
    //     uni.setStorageSync(importDataKey, response)

    //     uni.navigateTo({
    //       url: `/pages/import-detail/index?url=${encodeURIComponent(firstUrl)}&dataKey=${importDataKey}`,
    //     })
    //   }, 500)
    // }
    // else {
    //   uni.showToast({
    //     title: '解析失败，请检查链接是否正确',
    //     icon: 'error',
    //   })
    // }
  }
  catch (error) {
    uni.hideLoading()
    console.error('解析链接失败:', error)

    // 显示更友好的错误提示
    uni.showModal({
      title: '解析失败',
      content: '无法解析该链接，可能是网络问题或网站结构发生变化。是否继续手动导入？',
      confirmText: '继续导入',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 创建基础数据对象
          const basicData = {
            platform: platform.id,
            originalUrl: firstUrl,
          }

          // 将基础数据存储到 localStorage
          const importDataKey = `import_data_${Date.now()}`
          uni.setStorageSync(importDataKey, basicData)

          uni.navigateTo({
            url: `/pages/import-detail/index?url=${encodeURIComponent(firstUrl)}&platform=${platform.id}&dataKey=${importDataKey}`,
          })
        }
      },
    })
  }
}

// 解析平台 - 使用supportedPlatforms中的域名信息
function parsePlatform(url: string) {
  for (const platform of supportedPlatforms.value) {
    for (const domain of platform.domains) {
      if (url.includes(domain)) {
        return platform
      }
    }
  }
  return null
}

// 监听链接输入，自动识别平台
function handleUrlInput() {
  const url = importUrl.value.trim()
  if (!url) {
    detectedPlatform.value = ''
    return
  }

  // 处理多个URL的情况，取第一个进行识别
  const firstUrl = url.split('\n')[0].trim()
  const platform = parsePlatform(firstUrl)

  if (platform) {
    detectedPlatform.value = platform.name
  }
  else {
    detectedPlatform.value = ''
  }
}

// 添加到搜索历史
function addToHistory(keyword: string) {
  // 检查是否已存在
  if (searchHistory.value.includes(keyword)) {
    return
  }

  searchHistory.value.unshift(keyword)

  // 限制历史记录数量
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }

  // 保存到本地存储
  uni.setStorageSync('searchHistory', searchHistory.value)
}

// 删除历史记录项
function deleteHistoryItem(index: number) {
  searchHistory.value.splice(index, 1)
  uni.setStorageSync('searchHistory', searchHistory.value)
}

// 清空历史记录
function clearHistory() {
  searchHistory.value = []
  uni.removeStorageSync('searchHistory')
  uni.showToast({
    title: '搜索历史已清空',
    icon: 'success',
  })
}

// 点击历史记录项
function handleHistoryClick(keyword: string) {
  searchKeyword.value = keyword
  handleSearch()
}

// 点击热门搜索
function handleHotSearchClick(keyword: string) {
  searchKeyword.value = keyword
  handleSearch()
}

// 点击搜索结果
function handleResultClick(result: any) {
  uni.navigateTo({
    url: `/pages/novel-detail/index?id=${result.id}`,
  })
}

// 格式化数量显示
function formatCount(count: number) {
  if (count >= 10000) {
    return `${(count / 10000).toFixed(1)}万`
  }
  if (count >= 1000) {
    return `${(count / 1000).toFixed(1)}k`
  }
  return count.toString()
}

// 页面加载时读取搜索历史
onMounted(() => {
  const history = uni.getStorageSync('searchHistory')
  if (history && Array.isArray(history)) {
    searchHistory.value = history
  }
})
</script>

<template>
  <view class="search-page bg-bg-dark" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
    <!-- 顶部标题栏 -->
    <view class="search-header">
      <view class="header-left">
        <i class="fas fa-search text-36rpx text-primary" />
        <text class="header-title">搜索导入</text>
      </view>
      <view class="header-right">
        <i class="fas fa-history text-32rpx text-text-muted" />
        <i class="fas fa-qrcode text-32rpx text-text-muted" />
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="page-content">
      <!-- 搜索区域 -->
      <section class="search-section">
        <view class="search-input-container">
          <i class="fas fa-search search-icon-large" />
          <input
            v-model="searchKeyword"
            type="text"
            class="search-input-large"
            placeholder="搜索小说名称、作者或关键词..."
            @confirm="handleSearch"
          >
        </view>
        <view class="search-buttons">
          <BaseButton variant="primary" class="flex-1" @click="handleSearch">
            <i class="fas fa-search" style="margin-right: 8rpx;" />
            <text>搜索</text>
          </BaseButton>
          <BaseButton variant="secondary" class="flex-1" @click="handleImport">
            <i class="fas fa-plus" style="margin-right: 8rpx;" />
            <text>导入链接</text>
          </BaseButton>
        </view>
      </section>

      <!-- 导入区域 -->
      <section class="import-section">
        <view class="import-area">
          <i class="fas fa-link import-icon" />
          <text class="import-text">将小说分享链接粘贴到下方输入框，系统将自动识别平台</text>

          <!-- 平台识别提示 -->
          <view v-if="detectedPlatform" class="platform-detected">
            <i class="fas fa-check-circle platform-check-icon" />
            <text class="platform-detected-text">已识别平台：{{ detectedPlatform }}</text>
          </view>

          <textarea
            v-model="importUrl"
            class="url-input"
            placeholder="请粘贴小说分享链接，支持多个链接批量导入&#10;例如：https://fanqienovel.com/page/xxxxx&#10;支持的平台：番茄小说、起点读书、晋江文学城、纵横中文网"
            :rows="3"
            :maxlength="5000"
            :show-confirm-bar="false"
            :auto-height="true"
            @input="handleUrlInput"
          />
          <BaseButton variant="primary" class="w-full" @click="handleImport">
            <i class="fas fa-download" style="margin-right: 8rpx;" />
            <text>开始导入</text>
          </BaseButton>
        </view>
      </section>

      <!-- 搜索历史 -->
      <section class="history-section">
        <view class="section-header">
          <text class="section-title">搜索历史</text>
          <text class="clear-history" @click="clearHistory">
            <i class="fas fa-trash" /> 清空
          </text>
        </view>
        <view class="history-list">
          <view
            v-for="(item, index) in searchHistory"
            :key="index"
            class="history-item"
            @click="handleHistoryClick(item)"
          >
            <view class="history-text">
              <i class="fas fa-clock" />
              <text>{{ item }}</text>
            </view>
            <i class="fas fa-times history-delete" @click.stop="deleteHistoryItem(index)" />
          </view>
        </view>
      </section>

      <!-- 热门搜索 -->
      <section class="hot-search">
        <text class="section-title">热门搜索</text>
        <view class="hot-search-grid">
          <view
            v-for="item in hotSearches"
            :key="item.rank"
            class="hot-search-item"
            @click="handleHotSearchClick(item.keyword)"
          >
            <view class="hot-rank" :class="[item.type]">
              {{ item.rank }}
            </view>
            <text class="hot-keyword">{{ item.keyword }}</text>
          </view>
        </view>
      </section>

      <!-- 搜索结果 -->
      <section v-if="showResults" class="results-section">
        <text class="section-title">搜索结果</text>
        <view class="results-list">
          <view
            v-for="result in searchResults"
            :key="result.id"
            class="result-item"
            @click="handleResultClick(result)"
          >
            <view class="result-platform">
              {{ result.platform }}
            </view>
            <view class="novel-card">
              <image :src="result.cover" class="novel-cover" mode="aspectFill" />
              <view class="novel-info">
                <view class="novel-main-info">
                  <text class="novel-title">{{ result.title }}</text>
                  <text class="novel-author">作者：{{ result.author }}</text>
                  <text class="novel-description">{{ result.description }}</text>
                </view>
                <view class="novel-meta">
                  <view class="meta-item">
                    <i class="fas fa-eye" />
                    <text class="meta-text">{{ formatCount(result.viewCount) }}</text>
                  </view>
                  <view class="meta-item">
                    <i class="fas fa-heart" />
                    <text class="meta-text">{{ formatCount(result.likeCount) }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </section>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.search-page {
  /* min-height: 100vh;
  padding-bottom: 120rpx; */
}

// 顶部标题栏样式
.search-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--background-medium);
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.header-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.header-right {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.page-content {
  /* padding: 0 var(--spacing-md); */
}

// 搜索区域样式
.search-section {
  background: linear-gradient(135deg, rgba(255, 107, 53, 0.85), rgba(255, 149, 0, 0.75));
  padding: var(--spacing-lg);
  border-radius: var(--border-radius);
  margin-bottom: var(--spacing-lg);
  box-shadow: 0 8rpx 32rpx rgba(255, 107, 53, 0.25);
}

.search-input-container {
  position: relative;
  margin-bottom: var(--spacing-md);
}

.search-input-large {
  width: 100%;
  padding: var(--spacing-md) var(--spacing-md) var(--spacing-md) 96rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: var(--border-radius);
  color: #333;
  font-size: 32rpx;
  backdrop-filter: blur(20rpx);
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.search-input-large::placeholder {
  color: #666;
  font-weight: 400;
}

.search-icon-large {
  position: absolute;
  left: var(--spacing-md);
  top: 50%;
  transform: translateY(-50%);
  color: #ff6b35;
  font-size: 40rpx;
  z-index: 1;
  transition: color 0.3s ease;
}

.search-input-large:focus {
  outline: none;
  background-color: rgba(255, 255, 255, 1);
  border-color: #ff6b35;
  box-shadow:
    0 0 0 4rpx rgba(255, 107, 53, 0.2),
    0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}

.search-input-large:focus + .search-icon-large {
  color: #ff6b35;
}

.search-buttons {
  display: flex;
  gap: var(--spacing-sm);
}

// 搜索区域按钮特殊样式
.search-buttons :deep(.bg-novel-primary) {
  background: linear-gradient(135deg, #ff6b35, #ff9500);
  box-shadow: 0 4rpx 16rpx rgba(255, 107, 53, 0.3);
}

.search-buttons :deep(.bg-bg-light) {
  background-color: rgba(255, 255, 255, 0.9);
  border-color: rgba(255, 107, 53, 0.3);
  color: #ff6b35;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.search-buttons :deep(button):active {
  transform: scale(0.98);
}

// 导入区域样式
.import-section {
  background-color: var(--background-medium);
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
  border: 4rpx dashed var(--border-color);
  transition: all 0.3s ease;
}

.import-area {
  text-align: center;
  cursor: pointer;
}

.import-icon {
  font-size: 96rpx;
  color: var(--primary-color);
  margin-bottom: var(--spacing-md);
}

.import-text {
  color: var(--text-secondary);
  margin-bottom: var(--spacing-md);
  display: block;
}

// 平台识别提示样式
.platform-detected {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: rgba(76, 175, 80, 0.1);
  border: 2rpx solid rgba(76, 175, 80, 0.3);
  border-radius: var(--spacing-xs);
  margin-bottom: var(--spacing-md);
  animation: fadeIn 0.3s ease;
}

.platform-check-icon {
  color: #4caf50;
  font-size: 28rpx;
}

.platform-detected-text {
  color: #4caf50;
  font-size: 28rpx;
  font-weight: 500;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.url-input {
  width: 100%;
  min-height: 120rpx;
  max-height: 300rpx;
  padding: var(--spacing-md);
  background-color: var(--background-light);
  border: 2rpx solid var(--border-color);
  border-radius: var(--border-radius);
  color: var(--text-primary);
  font-size: 28rpx;
  line-height: 1.5;
  margin-bottom: var(--spacing-md);
  resize: none;
  word-break: break-all;
  overflow-y: auto;
  transition: all 0.3s ease;
}

.url-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 4rpx rgba(255, 107, 53, 0.1);
}

// 搜索历史样式
.history-section {
  background-color: var(--background-medium);
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.section-title {
  font-size: var(--font-size-base);
  font-weight: 600;
  color: var(--text-primary);
}

.clear-history {
  font-size: 28rpx;
  color: var(--text-muted);
  cursor: pointer;
  transition: color 0.3s ease;
}

.clear-history:hover {
  color: var(--primary-color);
}

.history-list {
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-sm) 0;
  border-bottom: 2rpx solid var(--border-color);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.history-item:last-child {
  border-bottom: none;
}

.history-item:hover {
  background-color: var(--background-light);
  margin: 0 calc(-1 * var(--spacing-md));
  padding-left: var(--spacing-md);
  padding-right: var(--spacing-md);
  border-radius: var(--spacing-xs);
}

.history-text {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  color: var(--text-secondary);
  font-size: 28rpx;
}

.history-delete {
  color: var(--text-muted);
  cursor: pointer;
  padding: var(--spacing-xs);
  transition: color 0.3s ease;
}

.history-delete:hover {
  color: #ef4444;
}

// 热门搜索样式
.hot-search {
  background-color: var(--background-medium);
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.hot-search-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-sm);
}

.hot-search-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm);
  background-color: var(--background-light);
  border-radius: var(--spacing-xs);
  cursor: pointer;
  transition: all 0.3s ease;
}

.hot-search-item:hover {
  background-color: var(--primary-color);
  color: var(--text-primary);
}

.hot-rank {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: 600;
  border-radius: 8rpx;
}

.hot-rank.top1 {
  background-color: #ff6b35;
  color: white;
}

.hot-rank.top2 {
  background-color: #f7931e;
  color: white;
}

.hot-rank.top3 {
  background-color: #fcd34d;
  color: #333;
}

.hot-rank.other {
  background-color: var(--background-medium);
  color: var(--text-muted);
}

.hot-keyword {
  font-size: 28rpx;
}

// 搜索结果样式
.results-section {
  margin-bottom: var(--spacing-lg);
}

.results-list {
}

.result-item {
  background-color: var(--background-medium);
  border-radius: var(--border-radius);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-md);
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover {
  transform: translateY(-4rpx);
  box-shadow: 0 16rpx 48rpx var(--shadow-color);
}

.result-platform {
  display: inline-block;
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--primary-color);
  color: var(--text-primary);
  border-radius: 24rpx;
  font-size: 22rpx;
  font-weight: 500;
  margin-bottom: var(--spacing-sm);
}

.novel-card {
  display: flex;
  gap: var(--spacing-md);
}

.novel-cover {
  width: 160rpx;
  height: 240rpx;
  border-radius: var(--spacing-xs);
  object-fit: cover;
}

.novel-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.novel-main-info {
}

.novel-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
  display: block;
}

.novel-author {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-xs);
  display: block;
}

.novel-description {
  font-size: var(--font-size-sm);
  color: var(--text-muted);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.novel-meta {
  display: flex;
  gap: var(--spacing-md);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: var(--text-muted);
  font-size: 24rpx;
}

.meta-item i {
  font-size: 24rpx;
}

.meta-text {
  font-size: 24rpx;
}

.bottom-spacing {
  height: 120rpx;
}
</style>
